# Contributor: Carlo Landmeter <clandmeter@gmail.com>
# Maintainer: Natanael Copa <ncopa@alpinelinux.org>

# when changing _ver we *must* bump _rel
_name=zfs
_ver=0.8.4
_rel=0

_flavor=${FLAVOR:-lts}
_kpkg=linux-$_flavor
_kver=5.4.54
_krel=2

_kpkgver="$_kver-r$_krel"

# for custom kernels set $FLAVOR
_extra_flavors=
case $CARCH in
	x86|x86_64|aarch64) _extra_flavors="virt";;
esac

_kpkg=linux-$_flavor
_kabi="$_kver-$_krel-$_flavor"

pkgname=$_name-$_flavor
pkgver=$_kver
pkgrel=$(( $_krel + $_rel ))

pkgdesc="ZFS for Linux"
url="http://zfsonlinux.org"
arch="x86 x86_64 aarch64 ppc64le"
license="CDDL-1.0"
provides="spl-vanilla" # Mitigate upgrade conflicts
depends="$_kpkg=$_kpkgver"
depends_dev="glib-dev e2fsprogs-dev util-linux-dev libtirpc-dev
	$_kpkg-dev=$_kpkgver"

makedepends="$depends_dev automake autoconf libtool linux-headers"
install_if="zfs $_kpkg=$_kpkgver"
subpackages="$pkgname-dev"
source="https://github.com/zfsonlinux/zfs/releases/download/zfs-$_ver/zfs-$_ver.tar.gz"
builddir="$srcdir/$_name-$_ver"

for f in $_extra_flavors; do
	makedepends="$makedepends linux-$f-dev=$_kpkgver"
	subpackages="$subpackages zfs-$f:_extra"
done

prepare() {
	default_prepare
	# verify the kernel version
	local _kapkbuild=../../main/linux-$_flavor-/APKBUILD
	if [ -f $_kapkbuild ]; then
		(	. $_kapkbuild
			pkgname=$_name-$_flavor
			[ "$_kver" != "$pkgver" ] && die "please update _kver to $pkgver"
			[ "$_krel" != "$pkgrel" ] && die "please update _krel to $pkgrel"
			return 0
		)
	fi
	autoreconf -vif
}

build() {
	cd "$builddir"
	local flavor= kabi=
	for flavor in $_flavor $_extra_flavors; do
		kabi="$_kver-$_krel-$flavor"
		mkdir -p "$kabi"
		(cd $kabi
		../configure --prefix=/usr \
			--with-tirpc \
			--sysconfdir=/etc \
			--mandir=/usr/share/man \
			--infodir=/usr/share/info \
			--localstatedir=/var \
			--with-config=kernel \
			--with-linux=/usr/src/linux-headers-$kabi

		make
		)
	done
}

package() {
	cd "$builddir"
	local flavor= kabi=
	for flavor in $_flavor $_extra_flavors; do
		kabi="$_kver-$_krel-$flavor"
		(cd $kabi && make DESTDIR="$pkgdir" install)
	done
}

_extra() {
	local flavor=${subpkgname##*-}
	depends="linux-$flavor=$_kpkgver"
	install_if="zfs linux-$flavor=$_kpkgver"
	pkgdesc="ZFS for Linux: kernel modules for $flavor"

	kabi="$_kver-$_krel-$flavor"
	mkdir -p "$subpkgdir"/lib/modules
	mv "$pkgdir"/lib/modules/$kabi "$subpkgdir"/lib/modules
}

dev() {
	mkdir -p "$subpkgdir"/usr
	mv "$pkgdir"/usr/src "$subpkgdir"/usr
	default_dev
}

sha512sums="9086dc6a6262dd93ca6ec43f1b4c2e5c804deba708c8a7460b8531aa4802b0bf8cac0917a1a00e6af2e96d4a21cd68b85e226bf571bd94041d0325c457106eb1  zfs-0.8.4.tar.gz"
